package com.pk.springbootsy1.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.pk.springbootsy1.dto.TUserDto;
import com.pk.springbootsy1.entity.TUser;
import com.pk.springbootsy1.service.TUserService;
import com.pk.springbootsy1.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class TUserController {

    @Autowired
    private TUserService tUserService;

    //用户登录
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public SaResult login(@RequestParam("username") String username,
                         @RequestParam("password") String password) {

        if (tUserService.login(username, password)) {
            //登录成功
            StpUtil.login(tUserService.selectByUsername(username).getId());
            return SaResult.ok("登录成功");
        } else {
            return SaResult.error("登录失败");

        }
    }
    @Operation(summary = "是否登录")
    @GetMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    //查看所有用户
    @Operation(summary = "查看所有用户")
    @GetMapping("/list")
    @SaCheckRole("admin")
    public R<List<TUserDto>> list() {
        return R.ok(tUserService.listTUserDto());
    }

    //用户注册
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public R<Void> register(@RequestBody TUser tUser) {
        if (tUserService.register(tUser)) {
            return R.ok("注册成功");
        } else {
            return R.fail("注册失败");
        }
    }

    //重置密码
    @Operation(summary = "重置密码")
    @PutMapping("/reset")
    @SaCheckRole("admin")
    public R<Void> reset(@RequestBody TUser tUser) {
        if (tUserService.reset(tUser)) {
            return R.ok("重置成功");
        } else {
            return R.fail("重置失败");
        }
    }


}
